import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { deepClone } from '../../../utils/utils';
import { ICellRendererParams } from '@ag-grid-community/core';

@Component({
  selector: 'apes-cell-sort',
  template: `
    <div class="apes-cell-sort">
      <!--<span>{{show()}}</span>-->
<!--      <span>{{parent}}</span>-->
<!--      <ng-container *ngIf="secondary != 0">-->
<!--        <span>.{{secondary}}</span>-->
<!--      </ng-container>-->
<!--      <span>&#45;&#45;{{rowIndex}}</span>-->
      <span>{{rowIndex + 1}}</span>
    </div>
  `,
  styles: [`
    .apes-cell-sort {
      text-align: center;
    }
  `],
  // changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RenderSortComponent implements ICellRendererAngularComp {
  refresh(params: any): boolean {
    return false;
  }

  params: ICellRendererParams;
  ctx: any;

  rowIndex: any;
  sortKey: any;
  data = {};
  parent = 0;
  secondary = 0;
  name:any;
  test:any;
  constructor() {
  }

  multiple: boolean = false;

  agInit(params: ICellRendererParams): void {
    this.params = params;
    this.rowIndex = deepClone(this.params.rowIndex);
    this.ctx = params.context;

    if (params.hasOwnProperty('colDef')) {
      this.sortKey = deepClone(params.colDef['sortKey']);
      this.name = deepClone(params.colDef['field']);
    } else {
      this.sortKey = deepClone(params.column['colDef']['sortKey']);
      this.name = deepClone(params.column['colDef']['field']);
    }

    // clearTimeout(this.test);

    this.test = setTimeout(() => {
      this.show();
    }, 300);

  }

  getValue(): any {
    // this.show();
    // let result;
    // result = this.parent + '.' + this.secondary;
    // result = this.rowIndex;

    // return result;
  }

  show() {
    this.parent = 0;
    this.secondary = 0;
    let gridName = this.ctx.gridName;
    if (this.ctx.model.hasOwnProperty(gridName)) {
      let gridData = deepClone(this.ctx.model[gridName]);
      let showData;
      if(gridData.length != 0 && gridData[0].hasOwnProperty('inquirySelectFlag')){
        showData = gridData.filter(x => x.inquirySelectFlag == 1);
      }else {
        showData = gridData;
      }
      for (let i = 0; i <= this.rowIndex; i++) {
        if (showData[i]) {
          if (showData[i].hasOwnProperty(this.sortKey)) {
            this.secondary += 1;
          } else {
            this.parent += 1;
            this.secondary = 0;
          }
        } else {
          this.parent += 1;
        }
      }
    } else {
      this.parent = 1;
    }
    // console.log(this.params);
    // this.params.node.setDataValue(this.name, this.rowIndex);

  }

}
